/*************************************************************************
    > File Name: client.cpp
    > Author: Lancer
    > Mail: 18826075768@163.com
************************************************************************/

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/shm.h>
#include "shm_com.h"
using namespace std;

int main(){
    int id;
    id = shmget((key_t)1234, sizeof(struct shared_use_st), 0666 | IPC_CREAT);
    if(id == -1){
        fprintf(stderr, "shmget failed!\n");
        exit(EXIT_FAILURE);
    }
    void* shared_memory = (void*)0;
    shared_memory = shmat(id, (void*)0, 0);
    if(shared_memory == (void*)-1){
        fprintf(stderr, "shmat failed!\n");
        exit(EXIT_FAILURE);
    }

    printf("Memory attached at %X\n", (long)shared_memory);
    struct shared_use_st* stuff;
    stuff = (shared_use_st*)shared_memory;

    int ret = 1;
    char buffer[BUFSIZ];
    while(ret){
        while(stuff->written == 1){
            sleep(1);
            printf("waiting for client...\n");
        }
        printf("Enter some text: ");
        fgets(buffer, BUFSIZ, stdin);
        strncpy(stuff->text, buffer, TEXT_SZ);

        stuff->written = 1;
        if(strncmp(buffer, "end", 3) == 0){
            ret = 0;
        }
    }

    if(shmdt(shared_memory) == -1){
        fprintf(stderr, "shmdt failed!\n");
        exit(EXIT_FAILURE);
    }

    exit(EXIT_SUCCESS);
}